package com.spring.gll.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Iterator;

@Controller
@RequestMapping("/fileController")
public class FileController {
    /*方法一*/
    @RequestMapping("/uplode")
    public String uplode(@RequestParam("file") CommonsMultipartFile file)throws Exception{
        //用来检测程序运行的时间
        long startTime = System.currentTimeMillis();
//        getOriginalFilename 得到上传时的文件名
        System.out.println("fileName:" + file.getOriginalFilename());
        try {
            //FileOutputStream 文件输出流
            OutputStream os = new FileOutputStream("E:/" + new Date().getTime() + file.getOriginalFilename());
            //获取输入流  文件输入流
            InputStream is = file.getInputStream();
            int temp;
            //一个一个字节的读入
            while((temp = is.read()) != -1){
                os.write(temp);
            }
            os.flush();
            os.close();
            is.close();
            System.out.println("Success");
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "Success";
    }

    //采用spring提供的上传文件的方法
    @RequestMapping("/springUpload")
    public String springUplode(HttpServletRequest request)throws Exception{
        long startTime = System.currentTimeMillis();
        //将当前上下文初始化给 commonMutipartResover (多部分解析器)
        CommonsMultipartResolver mutipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有ecctype = "mutipart/form-data
        if(mutipartResolver.isMultipart(request)){
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //获取mutiRequest中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有的文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if(file != null){
                    //进行上传
                    String path = "E:/"+new Date().getTime() + file.getOriginalFilename();
                    file.transferTo(new File(path));
                }
            }
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "Success";
    }

    //文件下载
    @RequestMapping("/download")
    public void downLoad(HttpServletResponse res){
        String path = "E:\\" + "16229853164341df9532896419d41b8f301e0456dd2f2(1).jpg";
        File file = new File(path);
        //如果文件存在的话
        if(file.exists()){
//          setContentType  设置发送到客户端的响应的内容类型
            res.setContentType("application/jpg");
//            文件下载，指定默认名 　　
            res.addHeader("Content-Disposition","attachment;filename=img1.jpg");
            byte buffer[] = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = res.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }

            }
            catch(IOException e){
                System.out.println("error");
            }
            finally{
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        System.out.println("下载成功");
    }
}
